import 'package:flutter/services.dart';

class FlutterBridge {
  static final FlutterBridge _instance = FlutterBridge._();
  // Creates a [MethodChannel] with the specified [name] 与 native端保持一致
  final MethodChannel _bridge = const MethodChannel("FlutterBridge");

  final _listeners = {}; // {'methodName':方法引用(){}}  _listeners搜集所有注册监听的方法
  FlutterBridge._() {
    _bridge.setMethodCallHandler((MethodCall call) async {
      String method = call.method;
      if (_listeners[method] != null) {
        // 如果该method已经注册了监听，则当native发来消息时，这里注册的监听就能收到。
        // 并能在注册方法中进行处理
        return _listeners[method](call);
      }

      return null;
    });
  }

  static FlutterBridge getInstance() {
    return _instance;
  }

  void register (String methodName, Function(MethodCall) callback) {
    _listeners[methodName] = callback; // 注册监听
  }
  void unRegister (String methodName) {
    _listeners.remove(methodName);
  }

  void goPointedNativePage(Map params) {
    _bridge.invokeMethod('goPointedNativePage', params);
  }

  MethodChannel getMethodChannel() {
    return _bridge;
  }
}